<template>
    <div class="user">
        <el-card style="padding-right: 25px;margin: 10px 0;">
            <el-form style="display: flex;justify-content: space-between;align-items: center;">
                <el-form-item label="用户名">
                    <el-input placeholder="请输入用户名" v-model="keyWord" style="width: 120px;" size="small"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="small" @click="searchUser" :disabled="keyWord == ''">搜索</el-button>
                    <el-button type="primary" size="small" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card>
            <el-button type="primary" @click="addUser">添加</el-button>
            <el-button type="danger" @click="batchDelete" :disabled="selectChangeArr.length == 0">批量删除</el-button>
            <el-table border style="margin: 10px 0" :data="userList" @selection-change="selectChange">
                <el-table-column type="selection"></el-table-column>
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="ID" prop="id"></el-table-column>
                <el-table-column label="用户名字" prop="username"></el-table-column>
                <el-table-column label="用户名称" prop="name"></el-table-column>
                <el-table-column label="用户角色" prop="roleName" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip></el-table-column>
                <el-table-column label="更新时间" prop="updateTime" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" width="280">
                    <template #default="scope">
                        <el-button type="primary" icon="User" size="small" @click="setRoles(scope.row)">分配角色</el-button>
                        <el-button type="primary" icon="Edit" size="small" @click="updateUser(scope.row)">编辑</el-button>
                        <el-button type="danger" icon="Delete" size="small">删除</el-button>

                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 9]"
                layout="prev, pager, next, jumper,->, sizes,total" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
            <el-drawer v-model="drawer" direction="rtl" @close="clearUserInfo">
                <template #header>
                    <h4>{{ userParams.id ? '修改用户' : '添加用户' }}</h4>
                </template>
                <template #default>
                    <el-form label-width="auto" :rules="rules" :model="userParams" ref="ruleFormRef">
                        <el-form-item label="用户姓名" prop="username">
                            <el-input placeholder="请输入用户姓名" v-model="userParams.username"></el-input>
                        </el-form-item>
                        <el-form-item label="用户昵称" prop="name">
                            <el-input placeholder="请输入用户昵称" v-model="userParams.name"></el-input>
                        </el-form-item>
                        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                            <el-input placeholder="请输入用户密码" v-model="userParams.password"></el-input>

                        </el-form-item>

                    </el-form>
                </template>
                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="cancelClick">取消</el-button>
                        <el-button type="primary" @click="confirmClick">确定</el-button>
                    </div>
                </template>
            </el-drawer>
            <el-drawer v-model="roleDrawer">
                <template #header>
                    <h4>分配角色用户</h4>
                </template>
                <template #default>
                    <el-form>
                        <el-form-item label="用户姓名">
                            <el-input v-model="userParams.username" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="角色列表">
                            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                                @change="handleCheckAllChange">
                                全选
                            </el-checkbox>
                            <el-checkbox-group v-model="assignRoles" @change="handleCheckedCitiesChange">
                                <el-checkbox v-for="role in allRoleList" :key="role.id" :label="role">
                                    {{ role.roleName }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-form>
                </template>
                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="cancelClick">取消</el-button>
                        <el-button type="primary" @click="confirmClickSetRole">确认</el-button>
                    </div>
                </template>
            </el-drawer>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { useUserStore } from '@/stores/user'
import { reqUserList, reqAddOrUpdateUser, reqAllRole, reqSetRole, reqBatchDeleteUser } from '@/api/acl/user/index'
import { ElMessage, ElMessageBox } from 'element-plus';
const UserStore = useUserStore()
const currentPage = ref(1)
const pageSize = ref(3)
const total = ref(0)
const userList = ref<any>([])
const drawer = ref(false)
const roleDrawer = ref(false)
const checkAll = ref(false)
const isIndeterminate = ref(false)
const userParams = ref<any>({
    username: '',
    name: '',
    password: ''
})
const ruleFormRef = ref()
onMounted(() => {
    getUserList()
})
const getUserList = async () => {
    const res = await reqUserList(currentPage.value, pageSize.value, keyWord.value)

    if (res.code == 200) {
        userList.value = res.data.records
        total.value = res.data.total
    }
}
const handleSizeChange = () => {
    getUserList()
}
const handleCurrentChange = () => {
    getUserList()
}
const addUser = () => {
    drawer.value = true
}
const updateUser = (row: any) => {
    Object.assign(userParams.value, row)
    drawer.value = true
}
const cancelClick = () => {
    drawer.value = false
}
const confirmClick = async () => {
    await ruleFormRef.value.validate()

    if (UserStore.username == userParams.value.username) {
        ElMessageBox.confirm(
            '确定要修改当前账户的用户姓名吗 ?',
            'Warning',
            {
                confirmButtonText: 'OK',
                cancelButtonText: 'Cancel',
                type: 'warning',
            }
        )
            .then(async () => {
                const res = await reqAddOrUpdateUser(userParams.value)
                if (res.code == 200) {
                    ElMessage({
                        type: "success",
                        message: userParams.value.id ? '修改成功' : '添加成功'
                    })
                    getUserList()
                    drawer.value = false
                }
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消修改',
                })
            })
    } else {
        const res = await reqAddOrUpdateUser(userParams.value)
        if (res.code == 200) {
            ElMessage({
                type: "success",
                message: userParams.value.id ? '修改成功' : '添加成功'
            })
            getUserList()
            drawer.value = false
        }
    }

    // if (UserStore.username == userParams.value.username) {
    //     ElMessageBox.alert('确定要修改当前用户姓名吗?', '警告', {
    //         // if you want to disable its autofocus
    //         // autofocus: false,
    //         showCancelButton: true,
    //         confirmButtonText: 'OK',
    //         cancelButtonText: 'Cancel',
    //         callback: async (action: Action) => {
    //             const res = await reqAddOrUpdateUser(userParams.value)
    //             if (res.code == 200) {
    //                 ElMessage({
    //                     type: "success",
    //                     message: userParams.value.id ? '修改成功' : '添加成功'
    //                 })
    //                 getUserList()
    //                 drawer.value = false
    //             }
    //             ElMessage({
    //                 type: 'info',
    //                 message: `action: ${action}`,
    //             })
    //         },
    //     })
    // } else {
    //     const res = await reqAddOrUpdateUser(userParams.value)
    //     if (res.code == 200) {
    //         ElMessage({
    //             type: "success",
    //             message: userParams.value.id ? '修改成功' : '添加成功'
    //         })
    //         getUserList()
    //         drawer.value = false
    //     }
    // }

}
const clearUserInfo = () => {
    Object.assign(userParams.value, {
        username: '',
        name: '',
        password: '',
        id: 0
    })
    ruleFormRef.value.clearValidate('username')
    ruleFormRef.value.clearValidate('name')
    ruleFormRef.value.clearValidate('password')

}
const validateUsername = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('用户姓名不能为空'))
    } else {
        callback()
    }
}
const validateName = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('用户昵称不能为空'))
    } else {
        callback()
    }
}
const password = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('用户密码不能为空'))
    } else {
        callback()
    }
}
const rules = reactive({
    username: [{ validator: validateUsername, trigger: 'blur' }],
    name: [{ validator: validateName, trigger: 'blur' }],
    password: [{ validator: password, trigger: 'blur' }],
})
const allRoleList = ref<any>([])
const assignRoles = ref<any>([])
const setRoles = async (row: any) => {
    Object.assign(userParams.value, row)
    const res = await reqAllRole(userParams.value.id)
    if (res.code == 200) {
        allRoleList.value = res.data.allRolesList
        assignRoles.value = res.data.assignRoles
        roleDrawer.value = true
    }
}
const handleCheckAllChange = (value: any) => {
    assignRoles.value = value ? allRoleList.value : []
    isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === allRoleList.value.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < allRoleList.value.length
}
const confirmClickSetRole = async () => {
    const dataParms = {
        userId: userParams.value.id,
        roleIdList: assignRoles.value.map((item: any) => {
            return item.id
        })
    }
    const res = await reqSetRole(dataParms)
    if (res.code == 200) {
        roleDrawer.value = false
        getUserList()
    }

}
const selectChangeArr = ref([])
const selectChange = (value: any) => {
    selectChangeArr.value = value
}
const batchDelete = async () => {
    const idList = selectChangeArr.value.map((item: any) => {
        return item.id
    })
    await reqBatchDeleteUser(idList)
    getUserList()

}
const keyWord = ref('')
const searchUser = () => {
    getUserList()
    keyWord.value = ''

}
const reset = () => {
    keyWord.value = ''
    getUserList()
}
</script>

<style lang="scss" scoped>
.user {
    padding: 10px;
}
</style>